<template>
  <div class="container">
    <div class="btn-collapse" @click="activate">
      <i
        :class="
          $store.state.menuCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'
        "
      ></i>
    </div>
    <el-breadcrumb separator="/">
      <transition-group name="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
          <!-- 最后一级和其上级分开渲染，以便处理跳转逻辑 -->
          <span v-if="index == levelList.length - 1">{{
            item.meta.title
          }}</span>
          <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>

<script>
export default {
  data() {
    return {
      levelList: null,
    };
  },
  watch: {
    $route() {
      this.getBreadcrumb();
    },
  },
  created() {
    this.getBreadcrumb();
  },
  methods: {
    //折叠/展开菜单栏
    activate() {
      this.$store.commit("SET_COLLAPSE");
    },
    //从路由获取面包屑数据
    getBreadcrumb() {
      let matched = this.$route.matched.filter(
        (item) => item.meta && item.meta.title
      );
      //breadcrumb--可在路由设置不显示在面包屑上的页面名称
      this.levelList = matched.filter(
        (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false
      );
    },
    //面包屑跳转逻辑
    handleLink(item) {
      const { redirect, path } = item;
      //判断是否是一级路由--则不跳转
      if (path.match("/").length === 1) {
        return;
      }
      if (redirect) {
        this.$router.push(redirect);
        return;
      }
      this.$router.push(path);
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: 50px;
  display: flex;
  align-items: center;
  .btn-collapse {
    height: 100%;
    line-height: 50px;
    padding: 0 15px;
    font-size: 30px;
    cursor: pointer;
    &:hover {
      background-color: #ebeef5;
    }
  }
}
</style>
